package com.wing.purchase.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.purchase.model.entity.SupplierContacts;
import com.wing.purchase.model.entity.SupplierDue;
import com.wing.purchase.model.entity.SupplierDueEnclosure;
import com.wing.purchase.model.entity.SupplierInfo;
import com.wing.purchase.model.request.SupplierInfoForm;
import com.wing.purchase.model.response.SupplierInfoVO;
import com.wing.purchase.service.SupplierContactsService;
import com.wing.purchase.service.SupplierDueEnclosureService;
import com.wing.purchase.service.SupplierDueService;
import com.wing.purchase.service.SupplierInfoService;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author
 */
@Validated
@Api(value = "Admin-供应商表管理-审核通过", tags = "#/purchase/supplierInfoPass")
@RestController("supplierInfoPassController")
@RequestMapping("purchase/admin/supplierInfoPass")
@RequiredArgsConstructor
public class SupplierInfoPassController {

    private final SupplierInfoService supplierInfoService;
    private final SupplierDueService supplierDueService;
    private final SupplierDueEnclosureService supplierDueEnclosureService;
    private final SupplierContactsService supplierContactsService;


    @ApiOperation(value = "查询所有供应商表", notes = "搜索")
    @GetMapping("/list")
    public PageResult<SupplierInfoVO> list(
            @RequestParam(defaultValue = "1") Integer page
            , @RequestParam(defaultValue = "10") Integer limit
            , @RequestParam(defaultValue = "create_time") String sort
            , @RequestParam(defaultValue = "asc") String order
            , Integer filterGenerateOrder
            , Long enquiryId
            , String supplierIds
            , String corporateName
            , String filterInfo
            , Integer filterHasQuotationSupplier
            , Long supplierCategoryId
            , String categoryName) {

        Page<SupplierInfoVO> pg = new Page<>(page, limit);
        Map<String, Object> params = new HashMap<>();
        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            params.put("sort", sort);
            params.put("order", order);
        }
        if (null != filterGenerateOrder) {
            params.put("filterGenerateOrder", filterGenerateOrder);
        }
        if (null != enquiryId) {
            params.put("enquiryId", enquiryId);
        }
        if (null != supplierIds) {
            params.put("supplierIds", supplierIds);
        }
        if (null != filterHasQuotationSupplier) {
            params.put("filterHasQuotationSupplier", filterHasQuotationSupplier);
        }
        if (StringUtils.isNotBlank(corporateName)) {
            params.put("corporateName", corporateName);
        }
        if (StringUtils.isNotBlank(categoryName)) {
            params.put("categoryName", categoryName);
        }
        params.put("status", SupplierInfo.Status.pass);
        params.put("categoryId", supplierCategoryId);
        IPage<SupplierInfoVO> list = supplierInfoService.pageList4app(pg, params);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }


    @ApiOperation(value = "添加供应商表", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(@Validated(SupplierInfoForm.Add.class) SupplierInfoForm supplierInfoForm) {
        if (supplierInfoService.add(supplierInfoForm) > 0) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }


    @ApiOperation(value = "修改供应商表", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(@Validated(SupplierInfoForm.Update.class) SupplierInfoForm supplierInfoForm) {
        SupplierInfo supplierInfo = supplierInfoService.getById(supplierInfoForm.getId());
        if (supplierInfo == null) {
            return JsonResult.fail("修改失败！");
        }
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(SupplierInfo.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(supplierInfoForm, supplierInfo, copyOptions);
        if (supplierInfoService.updateById(supplierInfo)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }


    @ApiOperation(value = "删除供应商表", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "supplierInfoId", value = "供应商表id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/{id}")
    public JsonResult delete(@PathVariable("id") Long supplierInfoId) {
        //删除供应商 尽调信息和尽调附件一起删除  联系人也删除
        if (supplierInfoService.removeById(supplierInfoId) && supplierDueService.removeBySupId(supplierInfoId) && supplierDueEnclosureService.removeBySupId(supplierInfoId) && supplierContactsService.removeBySupId(supplierInfoId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }


    @ApiOperation(value = "删除供应商", notes = "批量删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "供应商id", required = true, dataType = "String", paramType = "query")
    })
    @PostMapping("/delBatch")
    public JsonResult delete(String ids) {

        if (StringUtils.isNotBlank(ids)) {
            List<Long> idList = new ArrayList<>();
            String[] idArray = ids.split(",");
            for (int i = 0; i < idArray.length; i++) {
                idList.add(Long.valueOf(idArray[i]));
            }//删除供应商 尽调信息和尽调附件一起删除 联系人也删除
            if (supplierInfoService.remove(new QueryWrapper<SupplierInfo>().in("id", idList)) && supplierDueService.remove(new QueryWrapper<SupplierDue>().in("pur_sup_id", idList)) && supplierDueEnclosureService.remove(new QueryWrapper<SupplierDueEnclosure>().in("pur_sup_id", idList)) && supplierContactsService.remove(new QueryWrapper<SupplierContacts>().in("corporate_id", idList))) {
                return JsonResult.success("删除成功");
            }
        } else {
            return JsonResult.fail("请选择数量");
        }

        return JsonResult.fail("删除失败");
    }

    @ApiOperation(value = "查询所有供应商", notes = "查询")
    @GetMapping("/getAll")
    public JsonResult getAll() {
        QueryWrapper<SupplierInfo> wrapper = new QueryWrapper<>();
        wrapper.select("id", "corporate_name");
        wrapper.eq("status", SupplierInfo.Status.pass);
        List<SupplierInfo> supplierInfoList = supplierInfoService.list(wrapper);
        return JsonResult.success(supplierInfoList);
    }


    @ApiOperation(value = "同步供应商", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @GetMapping("/syncGetSupplierList")
    public JsonResult syncGetSupplierList() {
        return supplierInfoService.getSupplierList();
    }

}
